/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import centralOperator from './centralOperator';
import config from '../config.js';

const JS_TAG = 'JS/Common/Permission helper: ';
const KEY_PERMISSION_REQUESTED = 'requestedPermissions';
const KEY_PERMISSION_GRANTED = 'grantedPermissions';
const KEY_CAN_REQUEST_PERMISSIONS = 'availablePermissions';

var onCheckPermissionResult = (resultJson) => {
  console.debug(JS_TAG + 'Check permission result: ' + JSON.stringify(resultJson));
  let permissionState = JSON.parse(resultJson.data).permissionState;
  if(!permissionState){
    console.error(JS_TAG + 'permissionState is empty.');
  }
  if (permissionState[KEY_PERMISSION_GRANTED].length == permissionState[KEY_PERMISSION_REQUESTED].length) {
    console.debug(JS_TAG + 'All permissions granted');
    promiseParams.resolve();
  } else {
    requestAvailablePermissions(permissionState[KEY_PERMISSION_GRANTED], permissionState[KEY_CAN_REQUEST_PERMISSIONS]);
  }
}

var requestAvailablePermissions = async function(grantedPermissions, availablePermissions) {
  for (let permission of config.mandatoryPermissions) {
    if (!grantedPermissions.includes(permission) && !availablePermissions.includes(permission)) {
      console.debug(JS_TAG + 'Permission: ' + permission + 'is forbidden.');
      promiseParams.reject({
        isPermissionForbidden: true
      });
      return;
    }
  }
  if (availablePermissions.length > 0) {
    console.debug(JS_TAG + 'Permission can still be requested');
    await centralOperator.onPermissionRequest(permissionRequestCallback);
    centralOperator.requestPermission({
      permissions: availablePermissions
    });
  } else {
    console.debug(JS_TAG + 'Permission cannot be requested, but mandatory permissions is granted:');
    promiseParams.resolve(true);
  }
}

var permissionRequestCallback = (permissionInfo) => {
  console.debug(JS_TAG + 'Request permission result: ' + JSON.stringify(permissionInfo));
  let permissionState = permissionInfo.permissionState;
  if (permissionState[KEY_PERMISSION_GRANTED].length == permissionState[KEY_PERMISSION_REQUESTED].length) {
    console.debug(JS_TAG + 'All permissions granted');
    promiseParams.resolve();
    return;
  }
  let grantedPermissions = permissionState[KEY_PERMISSION_GRANTED];
  for (let permission of config.mandatoryPermissions) {
    if (!grantedPermissions.includes(permission)) {
      console.debug(JS_TAG + 'Permission: ' + permission + 'is forbidden.');
      promiseParams.reject({
        isPermissionForbidden: false
      });
      return;
    }
  }
  console.debug(JS_TAG + 'Mandatory permissions is granted:');
  promiseParams.resolve(true);
}

var promiseParams = {}

export default {
  data: {},
  checkAndRequestPermission() {
    let promise = new Promise((resolve, reject) => {
      promiseParams.resolve = resolve;
      promiseParams.reject = reject;
      centralOperator.checkPermission({
        permissions: config.permissions,
        success: onCheckPermissionResult,
      })
    })
    return promise;
  }
}